package com.lingjtx.im.core.distribute;

import com.lingjtx.common.core.constant.Const;
import com.lingjtx.common.core.constant.MqConst;
import com.lingjtx.common.core.constant.RedisConfig;
import com.lingjtx.common.core.model.mq.ImMessageBody;
import com.lingjtx.common.redis.service.IRedisService;
import com.lingjtx.im.core.common.SessionManager;
import com.lingjtx.im.core.handle.ImMessageHandle;
import com.lingjtx.im.core.protocol.MessageProto;
import org.springframework.stereotype.Service;

@Service
public class PrivateMessage implements ImMessageHandle {

    private final IRedisService redisService;
    private final MessagePublisher publisher;

    public PrivateMessage(IRedisService redisService, MessagePublisher publisher) {
        this.redisService = redisService;
        this.publisher = publisher;
    }

    @Override
    public void process(MessageProto.IMMessage message, byte version) {

        ImMessageBody body = new ImMessageBody();
        body.setMsgId(message.getMsgId());
        body.setMsgType(message.getMsgType());
        body.setContent(message.getContent());
        body.setSenderId(message.getSenderId());
        body.setReceiverId(message.getReceiverId());
        body.setTimestamp(message.getTimestamp());
        // 持久化本条消息到数据库
        publisher.publish(MqConst.IM_QUEUE_PRIVATE_CHAT, body);

        // 判断是否在线，
        if (!SessionManager.isUserOnline(message.getReceiverId(), redisService)) {
            //  如果用户在线，专属 node 消费，供该节点推送 WebSocket
            String nodeId = (String) redisService.get(RedisConfig.IM_USER_ONLINE + message.getReceiverId());
            publisher.publish(MqConst.IM_ROUTING_NODE_KEY + nodeId, message);
        } else {
            // 若不在线才推送通知（在线的会在专属 node 消费）
            publisher.publish(MqConst.QUEUE_NOTIFICATION_PUSH, body);
        }
    }

    @Override
    public byte getImType() {
        return Const.IMMsgType.PRI_CHAT;
    }
}
